﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ERPStudio;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
using RelationTextBox;

namespace ERPForms
{
    public partial class ConturiSpecialeAllFrm : FrmTreeRezumat
    {
        private String InitValue = String.Empty;
        private String oldID = string.Empty;

        public ConturiSpecialeAllFrm(ModuleClass mc):base(mc)
        {
            InitializeComponent();
            workConnString = mc.workConnectionString;
            HandleFillTree += new TreeLoadHandler(ConturiSpecialeFrm_HandleFillTree);
            newTreeDataControl = true;   
        }

        void ConturiSpecialeFrm_HandleFillTree(object sender, TreeViewEventArgs e)
        {
            if (oldID != String.Empty)
                UpdatePropBindingSource(oldID);
            dscTreeView.DataTreeViewNode nd = e.Node as dscTreeView.DataTreeViewNode;
            NameLabel.Text = nd.ToolTipText;
            LoadPropBindingSource(nd.ID.ToString());
            oldID = nd.ID.ToString();
            InitValue = GetPropValue();
        }

        private void ConturiSpecialeFrm_Load(object sender, EventArgs e)
        {
            SqlConnection con = DeschideConexiune(workConnString);
            this.conturiTableAdapter.Connection = con;
            this.conturiTableAdapter.FillByUnitateCategorie(this.eSRPDataSet.Conturi, ModuleInfo.CodUnitate);
            this.conturiSpecialeTableAdapter.Connection = con;
            this.conturiSpecialeTableAdapter.FillByUnitate(this.eSRPDataSet.ConturiSpeciale, ModuleInfo.CodUnitate);
            InchideConexiune(con);

            AddBindingSource(conturiSpecialeBindingSource);
            listTableAdaptor.Add(conturiSpecialeTableAdapter.Adapter);

            ConturiTV.ExpandAll();
        }

        private String GetPropValue()
        {
            String rez = String.Empty;
            if (PropCLB.GetItemCheckState(0) == CheckState.Checked)
                rez += "{AA}";
            if (PropCLB.GetItemCheckState(1) == CheckState.Checked)
                rez += "{REX}";
            if (PropCLB.GetItemCheckState(2) == CheckState.Checked)
                rez += "{CCS}";
            if (PropCLB.GetItemCheckState(3) == CheckState.Checked)
                rez += "{CA}";
            if (PropCLB.GetItemCheckState(4) == CheckState.Checked)
                rez += "{CD}";
            if (PropCLB.GetItemCheckState(5) == CheckState.Checked)
                rez += "{AB}";
            if (PropCLB.GetItemCheckState(6) == CheckState.Checked)
                rez += "{AL}";
            if (PropCLB.GetItemCheckState(7) == CheckState.Checked)
                rez += "{EAL}";
            if (PropCLB.GetItemCheckState(8) == CheckState.Checked)
                rez += "{FRZ}";
            if (PropCLB.GetItemCheckState(9) == CheckState.Checked)
                rez += "{TGC}";
            if (PropCLB.GetItemCheckState(10) == CheckState.Checked)
                rez += "{CSS}";
            if (PropCLB.GetItemCheckState(11) == CheckState.Checked)
                rez += "{TVA.DED}";
            if (PropCLB.GetItemCheckState(12) == CheckState.Checked)
                rez += "{TVA.COL}";
            if (PropCLB.GetItemCheckState(13) == CheckState.Checked)
                rez += "{TVA.NED}";
            if (PropCLB.GetItemCheckState(14) == CheckState.Checked)
                rez += "{ADA}";
            if (PropCLB.GetItemCheckState(15) == CheckState.Checked)
                rez += "{CLT}";
            if (PropCLB.GetItemCheckState(16) == CheckState.Checked)
                rez += "{BUG}";
            return rez;        
        }

        private void UpdatePropBindingSource(String Cont)
        {
            String rez = GetPropValue();
            int cate = 0;
            SqlConnection con = DeschideConexiune(workConnString);
            #region Verifica unicitatea conturilor de TVA
            if (rez.Contains("{TVA.DED}"))
            {
                SqlCommand cmd2 = new SqlCommand("SELECT COUNT(*)  FROM[ConturiSpeciale] WHERE [Tipuri]='{TVA.DED}' AND [CodUnitate]=" + ModuleInfo.CodUnitate + " AND [Cont]<>'" +
                Cont + "'", con);
                cate = Convert.ToInt32(cmd2.ExecuteScalar());
                if (cate != 0)
                {
                    MessageBox.Show("Exista definit un cont pentru TVA deductibil!", "Eroare", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    InchideConexiune(con);
                    return;
                }
            }

            if (rez.Contains("{TVA.COL}"))
            {
                SqlCommand cmd2 = new SqlCommand("SELECT COUNT(*)  FROM[ConturiSpeciale] WHERE [Tipuri]='{TVA.COL}' AND [CodUnitate]=" + ModuleInfo.CodUnitate + " AND [Cont]<>'" +
                Cont + "'", con);
                cate = Convert.ToInt32(cmd2.ExecuteScalar());
                if (cate != 0)
                {
                    MessageBox.Show("Exista definit un cont pentru TVA colectat!", "Eroare", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    InchideConexiune(con);
                    return;
                }
            }

            #endregion
            InchideConexiune(con);

            if (InitValue != rez)
            {
                ESRPDataSet.ConturiSpecialeRow newRow = ((DataRowView)conturiSpecialeBindingSource.Current).Row as ESRPDataSet.ConturiSpecialeRow;
                if (newRow != null)
                {
                    newRow.Tipuri = rez;
                }
                conturiSpecialeBindingSource.EndEdit();
            }
            else
                conturiSpecialeBindingSource.CancelEdit();
        }

        private void UpdateProp(String Cont)
        {
            String rez = GetPropValue();
            int cate = 0;
            SqlConnection con = DeschideConexiune(workConnString);
            #region Verifica unicitatea conturilor de TVA
            if (rez.Contains("{TVA.DED}"))
            {
                SqlCommand cmd2 = new SqlCommand("SELECT COUNT(*)  FROM[ConturiSpeciale] WHERE [Tipuri]='{TVA.DED}' AND [CodUnitate]=" + ModuleInfo.CodUnitate + " AND [Cont]<>'" +
                Cont + "'", con);
                cate = Convert.ToInt32(cmd2.ExecuteScalar());
                if (cate != 0)
                {
                    MessageBox.Show("Exista definit un cont pentru TVA deductibil!", "Eroare", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    InchideConexiune(con);
                    return;
                }
            }

            if (rez.Contains("{TVA.COL}"))
            {
                SqlCommand cmd2 = new SqlCommand("SELECT COUNT(*)  FROM[ConturiSpeciale] WHERE [Tipuri]='{TVA.COL}' AND [CodUnitate]=" + ModuleInfo.CodUnitate + " AND [Cont]<>'" +
                Cont + "'", con);
                cate = Convert.ToInt32(cmd2.ExecuteScalar());
                if (cate != 0)
                {
                    MessageBox.Show("Exista definit un cont pentru TVA colectat!", "Eroare", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    InchideConexiune(con);
                    return;
                }
            }

            #endregion


            SqlCommand cmd = new SqlCommand("UPDATE [ConturiSpeciale] SET [Tipuri]='" + rez + "' WHERE [CodUnitate]=" + ModuleInfo.CodUnitate + " AND [Cont]='" +
                Cont + "'", con);
            if (InitValue != rez)
            {
                if (InitValue == String.Empty)
                {
                    cmd.CommandText = "INSERT INTO [ConturiSpeciale]([Cont],[CodUnitate],[Tipuri],[Descriere]) VALUES ('" + Cont + "'," + ModuleInfo.CodUnitate.ToString() +
                        ",'" + rez + "','')";
                }
                if (rez == String.Empty)
                {
                    cmd.CommandText = "DELETE FROM [ConturiSpeciale] WHERE [CodUnitate]=" + ModuleInfo.CodUnitate + " AND [Cont]='" +
                        Cont + "'";
                }
                try
                {
                    cate += cmd.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    TrateazaExceptie(ex);
                }
            }
            
            SetStatus("S-au salvat " + cate.ToString() + " inregistrari la: " + DateTime.Now.ToString());

            InchideConexiune(cmd.Connection);

        }

        public void LoadProp(String Cont)
        {
            for(int i=0; i<PropCLB.Items.Count;i++)
                 PropCLB.SetItemChecked(i, false);

            SqlCommand cmd = new SqlCommand("SELECT [Tipuri] FROM [ConturiSpeciale] WHERE [CodUnitate]=" + ModuleInfo.CodUnitate.ToString() + " AND [Cont]='" +
            Cont + "'", DeschideConexiune(workConnString));
            Object rez = cmd.ExecuteScalar();
            if (rez != null && rez != DBNull.Value)
            {
                InitValue = rez.ToString().ToUpper();
                MatchCollection m = Regex.Matches(InitValue,
                @"(\s*{(?<valoare>AA|REX|CA|CD|AB|AL|EAL|CCS|FRZ|TGC|CSS|TVA.DED|TVA.COL|TVA.NED|ADA|CLT|BUG)}\s*)");

                foreach (Match mp in m)
                {
                    if (mp.Success == true)
                    {
                        if (mp.Value == "{AA}")
                            PropCLB.SetItemChecked(0, true);
                        if (mp.Value == "{REX}")
                            PropCLB.SetItemChecked(1, true);
                        if (mp.Value == "{CCS}")
                            PropCLB.SetItemChecked(2, true);
                        if (mp.Value == "{CA}")
                            PropCLB.SetItemChecked(3, true);
                        if (mp.Value == "{CD}")
                            PropCLB.SetItemChecked(4, true);
                        if (mp.Value == "{AB}")
                            PropCLB.SetItemChecked(5, true);
                        if (mp.Value == "{AL}")
                            PropCLB.SetItemChecked(6, true);
                        if (mp.Value == "{EAL}")
                            PropCLB.SetItemChecked(7, true);
                        if (mp.Value == "{FRZ}")
                            PropCLB.SetItemChecked(8, true);
                        if (mp.Value == "{TGC}")
                            PropCLB.SetItemChecked(9, true);
                        if (mp.Value == "{CSS}")
                            PropCLB.SetItemChecked(10, true);
                        if (mp.Value == "{TVA.DED}")
                            PropCLB.SetItemChecked(11, true);
                        if (mp.Value == "{TVA.COL}")
                            PropCLB.SetItemChecked(12, true);
                        if (mp.Value == "{TVA.NED}")
                            PropCLB.SetItemChecked(13, true);
                        if (mp.Value == "{ADA}")
                            PropCLB.SetItemChecked(14, true);
                        if (mp.Value == "{CLT}")
                            PropCLB.SetItemChecked(15, true);
                        if (mp.Value == "{BUG}")
                            PropCLB.SetItemChecked(16, true);

                    }
                }
            }
            InchideConexiune(cmd.Connection);
        }

        public void LoadPropBindingSource(String Cont)
        {
            for (int i = 0; i < PropCLB.Items.Count; i++)
                PropCLB.SetItemChecked(i, false);

            int index = conturiSpecialeBindingSource.Find("Cont", Cont);

            if (index >= 0)
            {
                conturiSpecialeBindingSource.Position = index;
                ESRPDataSet.ConturiSpecialeRow newRow = ((DataRowView)conturiSpecialeBindingSource.Current).Row as ESRPDataSet.ConturiSpecialeRow;

                InitValue = newRow.Tipuri.ToUpper();
                MatchCollection m = Regex.Matches(InitValue,
                @"(\s*{(?<valoare>AA|REX|CA|CD|AB|AL|EAL|CCS|FRZ|TGC|CSS|TVA.DED|TVA.COL|TVA.NED|ADA|CLT|BUG)}\s*)");

                foreach (Match mp in m)
                {
                    if (mp.Success == true)
                    {
                        if (mp.Value == "{AA}")
                            PropCLB.SetItemChecked(0, true);
                        if (mp.Value == "{REX}")
                            PropCLB.SetItemChecked(1, true);
                        if (mp.Value == "{CCS}")
                            PropCLB.SetItemChecked(2, true);
                        if (mp.Value == "{CA}")
                            PropCLB.SetItemChecked(3, true);
                        if (mp.Value == "{CD}")
                            PropCLB.SetItemChecked(4, true);
                        if (mp.Value == "{AB}")
                            PropCLB.SetItemChecked(5, true);
                        if (mp.Value == "{AL}")
                            PropCLB.SetItemChecked(6, true);
                        if (mp.Value == "{EAL}")
                            PropCLB.SetItemChecked(7, true);
                        if (mp.Value == "{FRZ}")
                            PropCLB.SetItemChecked(8, true);
                        if (mp.Value == "{TGC}")
                            PropCLB.SetItemChecked(9, true);
                        if (mp.Value == "{CSS}")
                            PropCLB.SetItemChecked(10, true);
                        if (mp.Value == "{TVA.DED}")
                            PropCLB.SetItemChecked(11, true);
                        if (mp.Value == "{TVA.COL}")
                            PropCLB.SetItemChecked(12, true);
                        if (mp.Value == "{TVA.NED}")
                            PropCLB.SetItemChecked(13, true);
                        if (mp.Value == "{ADA}")
                            PropCLB.SetItemChecked(14, true);
                        if (mp.Value == "{CLT}")
                            PropCLB.SetItemChecked(15, true);
                        if (mp.Value == "{BUG}")
                            PropCLB.SetItemChecked(16, true);

                    }
                }
            }
            else
            { 
                ///not record for cont
                ///
                conturiSpecialeBindingSource.AddNew();
                ESRPDataSet.ConturiSpecialeRow newRow = ((DataRowView)conturiSpecialeBindingSource.Current).Row as ESRPDataSet.ConturiSpecialeRow;
                if (newRow != null)
                {
                    newRow.Cont = Cont;
                    newRow.CodUnitate = ModuleInfo.CodUnitate;
                    newRow.Descriere = String.Empty;
                    newRow.Tipuri = String.Empty;
                }
            }

        }

    }
}
